;(function(){
  const grid = document.getElementById('video-grid')
  const loading = document.getElementById('loading')
  const errorBox = document.getElementById('error')

  async function fetchHotVideos(){
    loading.hidden = false
    errorBox.hidden = true
    try{
      // 占位接口：由后端实现实际查询与返回
      // 期望返回格式：{ items: [{ url, title, view_count, like_count }], ts }
      const res = await fetch('/api/hot-videos/', { headers: { 'Accept': 'application/json' } })
      if(!res.ok) throw new Error('HTTP '+res.status)
      const data = await res.json()
      render(data.items || [])
    }catch(err){
      console.error('加载热门视频失败:', err)
      errorBox.hidden = false
    }finally{
      loading.hidden = true
    }
  }

  function render(items){
    grid.innerHTML = ''
    if(!items.length){
      grid.innerHTML = '<p class="error">暂无数据</p>'
      return
    }
    for(const it of items){
      const card = document.createElement('article')
      card.className = 'video-card'
      const creator = it.creator || '热门创作者'
      card.innerHTML = `
        <div class="thumb">
          <span class="badge">HOT</span>
          <video src="${escapeHtml(it.url)}" controls preload="metadata"></video>
        </div>
        <div class="video-meta">
          <h3 class="title">${escapeHtml(it.title || '热门视频')}</h3>
          <div class="stats">播放 ${fmtNum(it.view_count)} · 赞 ${fmtNum(it.like_count)}</div>
        </div>
        <div class="video-actions" data-video-url="${escapeHtml(it.url)}" data-creator="${escapeHtml(creator)}">
          <button type="button" class="act-like">👍 点赞</button>
          <button type="button" class="act-comment">💬 评论</button>
          <button type="button" class="act-follow">➕ 关注</button>
          <button type="button" class="act-fav">⭐ 收藏</button>
        </div>
      `
      grid.appendChild(card)
    }

    // 绑定交互
    grid.querySelectorAll('.video-actions').forEach(box => {
      const videoUrl = box.getAttribute('data-video-url')
      const creator = box.getAttribute('data-creator')
      box.querySelector('.act-like')?.addEventListener('click', () => sendAction('like', { video_url: videoUrl }))
      box.querySelector('.act-comment')?.addEventListener('click', async () => {
        const content = prompt('输入评论内容：')
        if(content && content.trim()) sendAction('comment', { video_url: videoUrl, content: content.trim() })
      })
      box.querySelector('.act-follow')?.addEventListener('click', () => sendAction('follow', { creator }))
      box.querySelector('.act-fav')?.addEventListener('click', () => sendAction('favorite', { video_url: videoUrl }))
    })
  }

  function fmtNum(n){
    if(n==null) return '-'
    if(n>=10000) return (n/10000).toFixed(1)+'万'
    return String(n)
  }

  function escapeHtml(str){
    return String(str).replace(/[&<>"]|'/g, s => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[s]))
  }

  fetchHotVideos()
  
  async function sendAction(type, payload){
    try{
      if(!window.IS_AUTH){
        alert('请先登录再进行此操作');
        window.redirectToLogin && window.redirectToLogin();
        return
      }
      const body = buildPayload(type, payload)
      await fetch('/api/request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
      })
      // 简单提示
      console.log('已发送', type, body)
    }catch(e){ console.error('发送失败', e) }
  }

  function buildPayload(type, ext){
    const ts = new Date().toISOString()
    const user = (window.CURRENT_USER||'').trim()
    switch(type){
      case 'like':
        return { operation:'insert', table:'like', data:{ user, ...ext, ts } }
      case 'comment':
        return { operation:'insert', table:'comment', data:{ user, ...ext, ts } }
      case 'follow':
        return { operation:'insert', table:'follow', data:{ follower: user, ...ext, ts } }
      case 'favorite':
        return { operation:'insert', table:'favorite', data:{ user, ...ext, ts } }
      default:
        return { operation:'noop', data:{ user, ts } }
    }
  }
  // 在进入热门页时，向 /api/request 发送一份查询 JSON（模仿注册时的 payload 结构）
  ;(async function sendQueryProbe(){
    const now = new Date()
    const payload = {
      request_id: `req-${now.getTime()}`,
      operation: 'query',
      database: 'short_video',
      table: 'video',
      fields: ['video_id','video_url','title','view_count','like_count','comment_count'],
      // 简化条件：最近7天 + 仅公开可见，服务端据此映射到真实 SQL
      condition: { upload_time_since_days: 7, visibility: 'public' },
      order_by: [
        { expr: 'view_count', desc: true },
        { expr: 'like_count', desc: true },
        { expr: 'comment_count', desc: true }
      ],
      limit: 20,
      purpose: 'hot_page_probe'
    }
    // 优先与注册相同：直连本地 mock；若不可用再尝试同源
    const endpoints = [
      'http://localhost:8080/api/request',
    ]
    for(const ep of endpoints){
      try{
        await fetch(ep, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
          mode: 'cors'
        })
        break
      }catch(e){
        // 尝试下一个候选端点
      }
    }
  })()
})();
